qdi// 系统设置API服务
const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const Authorization = require('../middleware/authorization');
const { getMongoDB } = require('../config/multi-database');

// 获取系统设置
router.get('/system-settings', authenticateToken, async (req, res) => {
    try {
        const db = await getMongoDB();
        const settingsCollection = db.collection('system_settings');
        
        // 获取系统设置，如果没有则创建默认设置
        let settings = await settingsCollection.findOne({ type: 'global' });
        
        if (!settings) {
            // 创建默认系统设置
            const defaultSettings = {
                type: 'global',
                website: {
                    title: 'ubike - 优质骑行装备',
                    description: '严选自行车、电动车及滑板车，匠心打造品质，支持全球配送，售后无忧',
                    keywords: '自行车,电动车,滑板车,骑行装备,体育用品',
                    logo: {
                        main: '/static/tp/Logo.png',
                        favicon: '/static/tp/Logo.png',
                        footer: '/static/tp/Logo.png'
                    },
                    contact: {
                        email: 'h3444850160@gmail.com',
                        address: '河北邢台',
                        phone: ''
                    },
                    social: {
                        wechat: '',
                        weibo: '',
                        instagram: '',
                        tiktok: ''
                    }
                },
                features: {
                    carouselEnabled: true,
                    blogEnabled: true,
                    productEnabled: true,
                    commentEnabled: false,
                    paymentEnabled: true,
                    membershipEnabled: false
                },
                seo: {
                    metaDescription: 'ubike - 严选自行车、电动车及滑板车，匠心打造品质，支持全球配送，售后无忧',
                    metaKeywords: '自行车,电动车,滑板车,骑行装备,体育用品',
                    googleAnalytics: '',
                    baiduAnalytics: ''
                },
                // 多语言配置
                language: {
                    multilingualEnabled: false,
                    defaultLanguage: 'zh-CN',
                    supportedLanguages: ['zh-CN'],
                    languageDetection: 'browser',
                    languageSwitcherPosition: 'header',
                    autoRedirect: true,
                    languageUrlFormat: 'subdirectory',
                    protectProperNouns: true,
                    protectedNouns: ['ubike', 'iPhone', 'Google', 'Microsoft', 'Apple', 'Samsung']
                },
                updatedAt: new Date(),
                updatedBy: 'system'
            };
            
            await settingsCollection.insertOne(defaultSettings);
            settings = defaultSettings;
        }
        
        res.json({
            success: true,
            data: settings
        });
    } catch (error) {
        console.error('获取系统设置失败:', error);
        res.status(500).json({
            success: false,
            message: '获取系统设置失败'
        });
    }
});

// 更新系统设置
router.put('/system-settings', authenticateToken, Authorization.requireRole(['admin']), async (req, res) => {
    try {
        const { website, features, seo } = req.body;
        const db = await getMongoDB();
        const settingsCollection = db.collection('system_settings');
        
        // 验证必填字段
        if (!website || !website.title) {
            return res.status(400).json({
                success: false,
                message: '网站标题为必填项'
            });
        }
        
        const updateData = {
            $set: {
                website: {
                    title: website.title || 'ubike - 优质骑行装备',
                    description: website.description || '',
                    keywords: website.keywords || '',
                    logo: website.logo || {
                        main: '/static/tp/Logo.png',
                        favicon: '/static/tp/Logo.png',
                        footer: '/static/tp/Logo.png'
                    },
                    contact: website.contact || {
                        email: 'h3444850160@gmail.com',
                        address: '河北邢台',
                        phone: ''
                    },
                    social: website.social || {}
                },
                features: features || {},
                seo: seo || {},
                updatedAt: new Date(),
                updatedBy: req.user.userId
            }
        };
        
        const result = await settingsCollection.updateOne(
            { type: 'global' },
            updateData,
            { upsert: true }
        );
        
        // 清除相关缓存
        clearSystemCache();
        
        res.json({
            success: true,
            message: '系统设置更新成功',
            data: {
                modifiedCount: result.modifiedCount
            }
        });
    } catch (error) {
        console.error('更新系统设置失败:', error);
        res.status(500).json({
            success: false,
            message: '更新系统设置失败'
        });
    }
});

// 更新网站基本信息
router.put('/system-settings/website', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const { title, description, keywords, contact, social } = req.body;
        const db = await getMongoDB();
        const settingsCollection = db.collection('system_settings');
        
        if (!title) {
            return res.status(400).json({
                success: false,
                message: '网站标题为必填项'
            });
        }
        
        const updateData = {
            $set: {
                'website.title': title,
                'website.description': description || '',
                'website.keywords': keywords || '',
                'website.contact': contact || {},
                'website.social': social || {},
                updatedAt: new Date(),
                updatedBy: req.user.userId
            }
        };
        
        const result = await settingsCollection.updateOne(
            { type: 'global' },
            updateData
        );
        
        clearSystemCache();
        
        res.json({
            success: true,
            message: '网站信息更新成功',
            data: {
                modifiedCount: result.modifiedCount
            }
        });
    } catch (error) {
        console.error('更新网站信息失败:', error);
        res.status(500).json({
            success: false,
            message: '更新网站信息失败'
        });
    }
});

// 更新Logo设置
router.put('/system-settings/logo', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const { logo } = req.body;
        const db = await getMongoDB();
        const settingsCollection = db.collection('system_settings');
        
        if (!logo || !logo.main) {
            return res.status(400).json({
                success: false,
                message: '主Logo为必填项'
            });
        }
        
        const updateData = {
            $set: {
                'website.logo': {
                    main: logo.main,
                    favicon: logo.favicon || logo.main,
                    footer: logo.footer || logo.main
                },
                updatedAt: new Date(),
                updatedBy: req.user.userId
            }
        };
        
        const result = await settingsCollection.updateOne(
            { type: 'global' },
            updateData
        );
        
        clearSystemCache();
        
        res.json({
            success: true,
            message: 'Logo设置更新成功',
            data: {
                modifiedCount: result.modifiedCount
            }
        });
    } catch (error) {
        console.error('更新Logo设置失败:', error);
        res.status(500).json({
            success: false,
            message: '更新Logo设置失败'
        });
    }
});

// 获取前端使用的系统设置（无需认证）
router.get('/system-settings/public', async (req, res) => {
    try {
        const db = await getMongoDB();
        const settingsCollection = db.collection('system_settings');
        
        const settings = await settingsCollection.findOne({ type: 'global' });
        
        if (!settings) {
            return res.json({
                success: true,
                data: {
                    website: {
                        title: 'ubike - 优质骑行装备',
                        description: '严选自行车、电动车及滑板车，匠心打造品质，支持全球配送，售后无忧',
                        logo: {
                            main: '/static/tp/Logo.png',
                            favicon: '/static/tp/Logo.png'
                        }
                    }
                }
            });
        }
        
        // 只返回前端需要的信息
        const publicData = {
            website: {
                title: settings.website.title,
                description: settings.website.description,
                logo: settings.website.logo
            }
        };
        
        res.json({
            success: true,
            data: publicData
        });
    } catch (error) {
        console.error('获取公开系统设置失败:', error);
        // 出错时返回默认设置
        res.json({
            success: true,
            data: {
                website: {
                    title: 'ubike - 优质骑行装备',
                    description: '严选自行车、电动车及滑板车，匠心打造品质，支持全球配送，售后无忧',
                    logo: {
                        main: '/static/tp/Logo.png',
                        favicon: '/static/tp/Logo.png'
                    }
                }
            }
        });
    }
});

// 清除系统缓存
function clearSystemCache() {
    // 这里可以集成Redis缓存清除逻辑
    console.log('系统缓存已清除');
}

module.exports = router;